package com.example.sunsg.okhttptest.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.breadtrip.R;
import com.example.sunsg.okhttptest.adapter.LifeStoryImagesAdapter;
import com.example.sunsg.okhttptest.adapter.LocalImageSelectAdapter;
import com.example.sunsg.okhttptest.bean.Image;
import com.example.sunsg.okhttptest.bean.LocalImageItem;
import com.example.sunsg.okhttptest.bean.LocalImageItemImage;
import com.example.sunsg.okhttptest.bean.LocalImageItemTitle;
import com.example.sunsg.okhttptest.bean.LocalItem;
import com.example.sunsg.okhttptest.bean.PreviewImage;
import com.example.sunsg.okhttptest.model.LifeStoryActivityModel;
import com.example.sunsg.okhttptest.util.Util;

import java.util.ArrayList;
import java.util.List;

public class LifeStoryActivity extends FragmentActivity implements View.OnClickListener ,LifeStoryActivityModel.CallBackLifeStoryActivity,LifeStoryImagesAdapter.AdapterCallBack {
    /**每行 几列*/
    public static final int COLUMNS_COUNT = 3;
    public static final int REQUEST_IMAGE_PREVIEW = 1;
    public static final String KEY_SELECTED_IMAGE = "key_selected_image";

    private ListView mListView;//图片文件列表
    private LifeStoryImagesAdapter mLifeStoryImagesAdapter;

    private LifeStoryActivityModel mLifeStoryActivityModel;

    private FragmentManager mFragmentManager;

    /**图片列表*/
    private RecyclerView mRecyclerView;
    private LocalImageSelectAdapter mLocalImageSelectAdapter;

    private TextView mTvTitle;

    private TextView mTvPreview;
    private TextView mTvDone;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_life_story);
        init();
        bindEvent();
    }

    /**
     * launch 方法
     * @param activity
     */
    public static void launch(Activity activity){
        Intent intent = new Intent(activity,LifeStoryActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data != null && resultCode == RESULT_OK){
            switch (requestCode){
                case REQUEST_IMAGE_PREVIEW:
                    List<PreviewImage> selectImageS = data.getParcelableArrayListExtra(KEY_SELECTED_IMAGE);
                    if(selectImageS != null){
                        List<LocalItem> items = new ArrayList<>();
                        LocalImageItemImage imageImage = null;
                        for(PreviewImage image : selectImageS){
                            for (LocalImageItem imgeItem : mLocalImageSelectAdapter.getmItems()){
                                if(imgeItem.getType() == LocalImageItem.TYPE_IMAGE){
                                    imageImage = (LocalImageItemImage) imgeItem.getChildItem();
                                    if(image.getPath().equals(imageImage.getImage().getDataPath())){
                                        if(image.isChecked()){
                                            imageImage.setChecked(true);
                                        }else{
                                            imageImage.setChecked(false);
                                            if(mLocalImageSelectAdapter.getChekedImages().contains(imageImage)){
                                                mLocalImageSelectAdapter.getChekedImages().remove(imageImage);
                                            }
                                        }

                                    }
                                }

                            }
                        }

                        mLocalImageSelectAdapter.notifyDataSetChanged();
                    }

                    break;
            }
        }
    }

    /**
     * 初始化view
     */
    private void init(){
        mFragmentManager = getSupportFragmentManager();
        mLifeStoryActivityModel = new LifeStoryActivityModel(this,getApplicationContext());
        LinearLayout llContainer = (LinearLayout) findViewById(R.id.ll_container);
        llContainer.setOnClickListener(this);

        mListView = (ListView) findViewById(R.id.listview);
        mLifeStoryImagesAdapter = new LifeStoryImagesAdapter(getApplicationContext());
        mListView.setAdapter(mLifeStoryImagesAdapter);

        initRecyclerView();

        mTvTitle = (TextView) findViewById(R.id.tv_title);
        mTvPreview = (TextView) findViewById(R.id.life_preview);
        mTvPreview.setEnabled(false);
        mTvPreview.setSelected(true);
        mTvDone = (TextView) findViewById(R.id.life_select_complete);
        mTvDone.setText(String.format(getString(R.string.finish_num),0));
    }

    /**
     * init RecyclerView
     * */
    private void initRecyclerView(){
        mRecyclerView = (RecyclerView) findViewById(R.id.recycle_view);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this,COLUMNS_COUNT);
        GridLayoutManager.SpanSizeLookup lookUp = new GridLayoutManager.SpanSizeLookup() {

            @Override
            public int getSpanSize(int position) {
                if(mLocalImageSelectAdapter.getItemCount() == 0 || mLocalImageSelectAdapter.getmItems() == null){
                    return 0;
                }
                int type = mLocalImageSelectAdapter.getmItems().get(position).getType();
                if(LocalImageItem.TYPE_TITLE == type){
                    return COLUMNS_COUNT;
                }

                if(LocalImageItem.TYPE_IMAGE == type){
                    return 1;
                }

                return COLUMNS_COUNT;
            }
        };

        gridLayoutManager.setSpanSizeLookup(lookUp);
        mRecyclerView.setLayoutManager(gridLayoutManager);
        mLocalImageSelectAdapter = new LocalImageSelectAdapter(getApplicationContext(),this);
        mRecyclerView.setAdapter(mLocalImageSelectAdapter);
        mRecyclerView.addItemDecoration(new SpacesItemDecoration());
    }



    public class SpacesItemDecoration extends RecyclerView.ItemDecoration{
        int cutPadding;
        int padding = Util.dp2px(getApplicationContext(), LocalImageSelectAdapter.IMAGE_PADDING);
        public SpacesItemDecoration() {
            int totalPadding = Util.dp2px(getApplicationContext(), LocalImageSelectAdapter.IMAGE_PADDING * (COLUMNS_COUNT - 1));
            cutPadding = totalPadding / COLUMNS_COUNT;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            ArrayList<LocalImageItem> items= mLocalImageSelectAdapter.getmItems();
            int adapterPosition = parent.getChildAdapterPosition(view);
            LocalImageItem item = items.get(adapterPosition);
            if(item.getType() == LocalImageItem.TYPE_IMAGE){
                LocalImageItemImage imageItem = (LocalImageItemImage) item.getChildItem();
                switch (imageItem.getIndex()){
                    case LocalImageItemImage.INDEX_LEFT:
                        outRect.left = 0;
                        outRect.right = cutPadding;
                        outRect.bottom = padding / 2;
                        outRect.top = padding / 2;
                        break;
                    case LocalImageItemImage.INDEX_MIDDLE:
                        outRect.left = cutPadding / 2;
                        outRect.right = cutPadding / 2;
                        outRect.bottom = padding / 2;
                        outRect.top = padding / 2;
                        break;
                    case LocalImageItemImage.INDEX_RIGHT:
                        outRect.left = cutPadding;
                        outRect.right = 0;
                        outRect.bottom = padding / 2;
                        outRect.top = padding / 2;
                        break;
                }
            }
        }
    }

    private void bindEvent(){
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                LocalItem localItem = mLifeStoryImagesAdapter.getItem(position);
                ArrayList<LocalImageItem> mItem = new ArrayList<LocalImageItem>();
                List<Image> images = mLifeStoryActivityModel.getImages(localItem.mBucketId);
                mLifeStoryActivityModel.sortImages(images);
                String date = null;
                int index = 0;
                for (Image image : images){
                    if(TextUtils.isEmpty(date) || !date.equals(mLifeStoryActivityModel.getDate(image))){
                        //添加日期
                        date = mLifeStoryActivityModel.getDate(image);
                        LocalImageItem item = new LocalImageItem(LocalImageItem.TYPE_TITLE,new LocalImageItemTitle(date));
                        mItem.add(item);
                        index = 0;
                    }
                    //添加图片
                    LocalImageItem item = new LocalImageItem(LocalImageItem.TYPE_IMAGE,new LocalImageItemImage(image,mLifeStoryActivityModel.getIndex(index)));
                    mItem.add(item);
                    index++;
                }

                mLocalImageSelectAdapter.setmItems(mItem);
                mLocalImageSelectAdapter.clearCheckeImages();
                hideImageList();
                mRecyclerView.scrollToPosition(mLocalImageSelectAdapter.getItemCount() - 1);
                mTvTitle.setText(localItem.mName);
            }
        });

        mTvPreview.setOnClickListener(this);
        mTvDone.setOnClickListener(this);

        ImageView imImage = (ImageView) findViewById(R.id.im_cancel);
        imImage.setOnClickListener(this);
    }

    /**隐藏图片列表*/
    private void hideImageList(){
        Animation anim = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.top_out);
        mListView.startAnimation(anim);
        mListView.setVisibility(View.GONE);
    }

    /**
     * 显示图片列表
     */
    private void showImageist(){
        mListView.setVisibility(View.VISIBLE);
        Animation anim = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.top_in);
        mListView.startAnimation(anim);
    }

    private void setSelectStatus(int count){
        if(count > 0){
            mTvPreview.setSelected(false);
            mTvPreview.setEnabled(true);
        }else{
            mTvPreview.setSelected(true);
            mTvPreview.setEnabled(false);
        }
        mTvDone.setText(String.format(getString(R.string.finish_num),count));
    }


    @Override
    public void setItems(List<LocalItem> itmes) {
        mLifeStoryImagesAdapter.setmItems(itmes);
    }

    @Override
    public void setSelect(int count) {
        setSelectStatus(count);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            /**标题*/
            case R.id.ll_container:
                showImageist();
                break;
            /**返回*/
            case R.id.im_cancel:
                finish();
                break;
            /**完成*/
            case R.id.life_select_complete:
                SpotEditActivity.launch(this,mLocalImageSelectAdapter.getChekedImages());
                break;
            /**预览*/
            case R.id.life_preview:
                ArrayList<LocalImageItemImage> images = mLocalImageSelectAdapter.getChekedImages();
                int checkCount = (images == null ? 0 : images.size());
                if(checkCount > 0){
                    ArrayList<PreviewImage> paths = new ArrayList<>();
                    PreviewImage previewImage = null;
                    Image image = null;
                    for (LocalImageItemImage imageItem : images){
                        image = imageItem.getImage();
                        previewImage = new PreviewImage(image.getWidth(),image.getHeight(),image.getDataPath(),true);
                        paths.add(previewImage);
                    }

                    ImagePreviewActivity.launch(LifeStoryActivity.this,paths,0,REQUEST_IMAGE_PREVIEW);
                }
                break;
        }
    }

}
